<?php

include("source/Connection.php");
include("source/Scripts.php");

$conn = new Connection();
$conn->connectToDatabase();
$conn->selectDatabase();

$url = htmlspecialchars($_POST['url']);
echo getLink($url,$conn);

//echo "<a href='".$urlCode."'>".$urlCode."</a>";

function getLink($url,$conn){

    $result = mysql_query("select s.short_url,s.click_count from path s where s.url like '%".$url."'");

    $row = mysql_fetch_row($result, MYSQL_NUM);

    if (!empty($row)) {
            $response = "{";
            $conn->closeConnection();
            $response = $response."\"link\":\"".$row[0]."\"";
            $response = $response.",\"clickCount\":\"".$row[1]."\"";
            $response = $response."}";
            return $response;

    }else{
            $urlCode = get_base_url()."/".generatePassword();
            $sql = mysql_query("insert into path(url, short_url,time,ip) values ('".$url."','".$urlCode."',NOW(),'".$_SERVER['REMOTE_ADDR']."')");
            if($sql){
                $conn->closeConnection();
                $response = "{";
                $response = $response."\"link\":\"".$urlCode."\"";
                $response = $response.",\"clickCount\":\""."0"."\"";
                $response = $response."}";
                return $response;
            }else{
                return "{\"link\":\"".'Error. Try again :('."\"}";
            }
    //echo "<a href='".$urlCode."'>".$urlCode."</a>";
    }

}

function generatePassword ($length = 5)
{
    $password = "";
    $possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDFGHIJKLMNOPQRSTUVWXYZ";

    $maxlength = strlen($possible);

    if ($length > $maxlength) {
        $length = $maxlength;
    }

    $i = 0;

    while ($i < $length) {
        $char = substr($possible, mt_rand(0, $maxlength-1), 1);
        if (!strstr($password, $char)) {
            $password .= $char;
            $i++;
        }
    }
    return $password;

}

